var prefix = jsctx + "/acctTenantOperator";
function listAcctRuleRepository1(ruleType,loadType) {
    //获取规则模板
    var operatorStationId = $("#operatorStationId").val();
    var acctRuleId = $("#acctRuleId").val();
    var ruleName='';
    if (ruleType == '0'){
        ruleName=$("#elecRuleName").val();
    }else if(ruleType == '1'){
        ruleName=$("#serviceRuleName").val();
    }else{
        ruleName=$("#gkdRuleName").val();
    }
    // alert(operatorStationId)
    $.ajax({
        "type": "POST",
        "url": prefix + "/listAcctRuleRepository",
        "data": {
            "operatorStationId": operatorStationId,
            "acctRuleId":acctRuleId,
            "ruleName":ruleName
        },
        "success": function (data) {
            $(".gkdRuleLiBrary .acctRuleWrap").html("");
            $(".gkdRuleLiBrary .elecRuleBtnWrap").html("");
            console.log(data)
            if (data.status == 200) {
                // if (data.data.acctSubItem.length>0) {
                //     for (var i = 0; i < data.data.acctSubItem.length; i++) {//子项回显
                //         var item = data.data.acctSubItem[i];
                //         for (var x in item) {
                //             var ruleName = x.split("_")[0];
                //             // var id = x.split("_")[1];
                //             filterRule(item[x], 'acctSubItem', ruleName)
                //         }
                //     }
                // }
                for (var i = 0; i < data.data.acctSubItemRepository.length; i++) {//自定义模板库
                    var item = data.data.acctSubItemRepository[i];
                    for (var x in item) {
                        var ruleName = x.split("_")[0];
                        var id = x.split("_")[1];
                        filterRule(item[x], 'acctSubItemRepository', ruleName, id)
                    }
                }
            } else {
                layer.msg("操作失败");
            }
        }
    })
    var copyBtnIndex = 1;
    var elecRuleListIndex = 1;
    var serviceRuleListIndex = 1;
    var gkdRuleListIndex = 1;
    var eleId = 4
    function filterRule(arr, ruleType, ruleName,id) {
        if (arr.length == 0) {
            return
        }
        if(ruleType=="acctSubItem"){
            var model_one = arr[0];
            var model_two = '';
            switch (arr[1]) {
                case 'a':
                    model_two = "平台服务费";
                    break;
                case 'b':
                    model_two = "平台电费";
                    break;
                case 'c':
                    model_two = "平台总金额";
                    break;
                case 'd':
                    model_two = "平台优惠金额";
                    break;
                case 'e':
                    model_two = "平台实收金额";
                    break;
                case 'f':
                    model_two = "平台电量";
                    break;
                case 'g':
                    model_two = "咨询订单金额";
                    break;
                default: model_two = arr[1]
            }
        }
        var patt1 = /[a-z]/;
        var patt2 = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
        var ruleBtn = '';
        var ruleContent = '';
        for (var i = 0; i < arr.length; i++) {
            if (patt1.test(arr[i])) {
                var buttonName;
                switch (arr[i]) {
                    case 'a':
                        buttonName = "平台服务费";
                        break;
                    case 'b':
                        buttonName = "平台电费";
                        break;
                    case 'c':
                        buttonName = "平台总金额";
                        break;
                    case 'd':
                        buttonName = "平台优惠金额";
                        break;
                    case 'e':
                        buttonName = "平台实收金额";
                        break;
                    case 'f':
                        buttonName = "平台电量";
                        break;
                    case 'g':
                        buttonName = "咨询订单金额";
                        break;
                }
                ruleBtn += "<button id='copy" + (copyBtnIndex + 1) + "' class='btn btn-lg copyBtn btn-default variable' draggable='true' ondragstart='drag(event)'>" + buttonName + "</button>"
                ruleContent += buttonName;
            } else if (patt2.test(arr[i])) {
                ruleBtn += "<button id='copy" + (copyBtnIndex + 1) + "' class='btn btn-lg copyBtn btn-default amountInputBlock' style='width:auto;padding: 0;' draggable='true' ondragstart='drag(event)'>" +
                    "<input type='input' value='" + arr[i] + "' class='amountInput'  onkeyup='clearNoNum(this)' placeholder='自定义数值' >" +
                    "</button>"
                ruleContent += arr[i];
            } else {
                ruleBtn += "<button id='copy" + (copyBtnIndex + 1) + "' class='btn btn-lg copyBtn btn-default symbol' draggable='true' ondragstart='drag(event)'>" + arr[i] + "</button>"
                ruleContent += arr[i];
            }
            copyBtnIndex++;
        }

        //判断交互类型
        if (ruleType == "acctSubItem") {
            // if($(".new_model:last").find(".drag_child3").html().indexOf("button")==-1){
            //     $(".new_model:last").remove()
            // }
            // $(".new_model").remove()
            var ruleContent = ruleBtn.substring(ruleBtn.indexOf("=</button>")+10)//找到等号的位置进行截取
            $('.new_label').append(` <div class="new_model" id="newModel"><button class="model_one">${model_one}</button> <input class="model_two" type="text" value="${model_two}"> <span class="model_three">=</span> <div id="div${eleId}" class="drag_child model_f drag_left drag_child3" ondragover="allowDrop(event)" ondrop="drop(event)">${ruleContent}</div><button class="btn input-distance templatesBtn model_six" type="gkd\"> 存入模板</button><button class="model_five delBtn">删除</button></div>`)
            eleId++
            // $(".finalRule3").html(ruleContent);
        }
        else if(ruleType == "acctSubItemRepository"){
            ruleBtn = "<div class=" + 'ruleBtnList' + gkdRuleListIndex + ">" + ruleBtn + "</div>"
            if (gkdRuleListIndex == 1) {
                var str = "<div class='acctRuleList' attrId='" + id + "'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + gkdRuleListIndex + ":<span>" +ruleContent + "</span>" + "</div>" +
                    "</div>"
            } else {
                var str = "<div class='acctRuleList' attrId='" + id + "'>" +
                    "<div class='choiceBox'>" + "<span class='redCircle hide'>" + "</span>" + "</div>" + "<div class='title'>" + ruleName + "</div>" +
                    "<div class='acctContent'>规则" + gkdRuleListIndex + ":<span>" +ruleContent + "</span>" + "</div>" +
                    "</div>"
            }
            $(".gkdRuleLiBrary .acctRuleWrap").append(str);
            $(".gkdRuleLiBrary .elecRuleBtnWrap").append(ruleBtn);
            gkdRuleListIndex++;
        }
    }
}

var count = 1;
var map = {};
function check1(string, showStr, index,modul,resultStr) {
    // 剔除空白符
    // console.log(index);
    string = string.replace(/[\r\n]/g, "").replace(/\ +/g, "");
    var flag = true;
    // 错误情况，空字符串
    if ("" === string) {
        // return false;
    }
    // if (/^[\x\÷\+\-\*\/]/.test(string)) {
    //     flag = false;
    //     console.error("运算符开头");
    // }

    //错误情况，运算符结尾
    if (/[\x\÷\+\-\*\/]$/.test(string)) {
        flag = false;
        console.error("运算符结尾");
    }

    // 错误情况，(后面是运算符或者)
    if (/\([\x\÷\+\-\*\/]/.test(string)) {
        flag = false;
        console.error("(后面是运算符");
    }
    // 错误情况，运算符连续
    if (/[\x\÷\+\-\*\/]{2,}/.test(string)) {
        flag = false;
        console.error("运算符连续");
    }
    // 空括号
    if (/\(\)/.test(string)) {
        flag = false;
        console.error("括号内为空");
    }
    // 错误情况，括号不配对
    var stack = [];
    for (var i = 0, item; i < string.length; i++) {
        item = string.charAt(i);
        if ('(' === item) {
            stack.push('(');
        } else if (')' === item) {
            if (stack.length > 0) {
                stack.pop();
            } else {
                flag = false;
                console.error("括号不匹配");
            }
        }
    }

    if (0 !== stack.length) {
        flag = false;
        console.error("空括号");
    }
    if (/\([\÷\+\-\*\/]/g.test(string)) {
        flag = false;
        console.error("(后面是运算符")
    }
    // 错误情况，)前面是运算符
    if (/[\÷\+\-\*\/]\)/g.test(string)) {
        flag = false;
        console.error(")前面是运算符")
    }
    var pop = string.split().length - 1;
    var editString = string;
    while (i < pop) {
        console.log(editString)
        if (/[\÷\+\-\*\/]\(/g.test(editString)) {
            editString = editString.substring(0, pop + 1);
            i++;
        } else {
            flag = false;
            console.error("(前面不是运算符");
        }

    }
    if (index == 1) {
        $(".drag_child1 .variable").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInput") || $(this).next().hasClass("amountInput")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
        $(".drag_child1 .amountInputBlock").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInputBlock") || $(this).next().hasClass("amountInputBlock")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
    } else if(index == 2){
        $(".drag_child2 .variable").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInput") || $(this).next().hasClass("amountInput")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
        $(".drag_child2 .amountInputBlock").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInputBlock") || $(this).next().hasClass("amountInputBlock")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
    }
    else if(index == 3){
        $(".drag_child3 .variable").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInput") || $(this).next().hasClass("amountInput")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
        $(".drag_child3 .amountInputBlock").each(function () {
            if ($(this).prev().hasClass("variable") || $(this).next().hasClass("variable") || $(this).prev().hasClass("amountInputBlock") || $(this).next().hasClass("amountInputBlock")) {
                console.error("变量之间没有符号");
                flag = false;
            }
        })
    }
    // // 错误情况，数字后面不是运算符或括号
    if (flag) {
        if(index==3){
            // $(".preview3").html("预览：结算服务费=" + showStr);
            $(".finalRule3").html(resultStr);
            $(".acctRuleModal").attr("type", "gkd");
            if (modul == "modul") {
                $(".acctRuleNameModal .ruleName").val("");
                $(".acctRuleNameModal").removeClass("hide").attr("type", "gkd");
            } else if (modul == "save") {

            } else {
                saveAcctRuleRepository(3, '')
            }
        }
        return true
        // $(".acctRuleModal").removeClass("hide");
    } else {
        alert("结算规则有误，请检查修正");
        return false
    }

}

$(".container-fluid").css("height", $(window).height() - 20);

layui.use('laydate', function () {
    var laydate = layui.laydate;

    //执行一个laydate实例
    var startDate = laydate.render({
        elem: '#ruleStartTime', //指定元素
        type: 'date',
        format: 'yyyy-MM-dd HH:mm:ss',
        trigger: 'click',
        position: 'fixed',
        done: function (value, date) {
            //console.log(value); //得到日期生成的值，如：2017-08-18
            //console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
            endDate.config.min = {
                year: date.year,
                month: date.month - 1,//关键(多了一个月，需要减1)
                date: date.date,
                hours: date.hours,
                minutes: date.minutes,
                seconds: date.seconds
            };
        }
    });
    var endDate = laydate.render({
        elem: '#ruleEndTime', //指定元素
        type: 'date',
        format: 'yyyy-MM-dd HH:mm:ss',
        trigger: 'click',
        position: 'fixed',
        done: function (value, date) {
            startDate.config.max = {
                year: date.year,
                month: date.month - 1,//关键(多了一个月，需要减1)
                date: date.date,
                hours: date.hours,
                minutes: date.minutes,
                seconds: date.seconds
            };
        }
    });
})

function hide(ele) {
    $("#elecRuleName").val("");
    $("#serviceRuleName").val("");
    $(ele).parents(".acctModal").addClass("hide");
    listAcctRuleRepository('','2');
}

$(".new_rule").on("click",".templatesBtn",function () {
    // console.log($(this).attr("type"));
    var that = $(this)
    if ($(this).attr("type") == "gkd"){
        var testStr = '';
        var showStr = '';
        var resultStr = '';
        that.siblings(".drag_child3").find(".copyBtn").each(function () {
            if ($(this).hasClass("variable")) {
                testStr += "[" + $(this).text() + "]"
                showStr += $(this).text();
                resultStr += $(this).text();
            } else if ($(this).children().length > 0) {
                testStr += Math.abs(parseFloat($(this).children('input').val()));
                showStr += "(" + $(this).children('input').val() + ")";
                resultStr += $(this).children('input').val();
            } else {
                testStr += $(this).text();
                showStr += $(this).text();
                resultStr += $(this).text();
            }
        })
        if (testStr == "") {
            alert("结算规则为空");
            return;
        }
        resultStr = (that.siblings(".model_one").html()+that.siblings(".model_two").val()+"="+resultStr).replace(/\s*/g,"")
        check1(testStr, showStr, 3, 'modul', resultStr)
    }

})


$(".gkdRuleLiBrary").on("click", ".acctRuleList", function () {
    $(this).find(".redCircle").removeClass("hide").parents(".acctRuleList").siblings(".acctRuleList").find(".redCircle").addClass("hide");
})

//编辑子项模板名称
$(".container-fluid").on("click","#gkdEditBtn",function () {
    // var ListIndex = 1;
    $(this).parents(".submitBlock").siblings(".acctRuleWrap").find(".redCircle").each(function (index) {
        if (!$(this).hasClass("hide")) {
            // ListIndex = index + 1;
            var ruleRepositoryId = $(this).parents(".acctRuleList").attr("attrId");
            var ruleName=$(this).parents(".acctRuleList").children(".title").html();
            $(".editAcctRuleModal").removeClass("hide").css("z-index",110);
            $(".editAcctRuleModal .ruleName").val(ruleName);
            $(".editAcctRuleModal .editNameConfirmBtn").unbind("click");
            $(".editAcctRuleModal .editNameConfirmBtn").click(function () {
                var editRuleName = $(".editAcctRuleModal .ruleName").val();
                if (editRuleName == "") {
                    alert("请填写规则名称");
                    return;
                }
                $.ajax({
                    "type": "POST",
                    "url": prefix + "/saveAcctRuleRepository",
                    "data": {
                        operatorStationId:$("#operatorStationId").val(),
                        tenantOperatorCode:$("#tenantOperatorCode").val(),
                        tenantCode:$("#tenantCode").val(),
                        ruleName : editRuleName,
                        ruleRepositoryId: ruleRepositoryId,
                    },
                    "success": function (data) {
                        if(data.status=="200"){
                            layer.msg("修改成功");
                            $(".editAcctRuleModal").addClass("hide");
                            listAcctRuleRepository('','2')
                        }
                    }
                })
            })
            return
        }
    })
})
var eleId = 4
$(".container-fluid").on("click",".libraryConfirmBtn",function () {
    var content = '';
    var ListIndex = 1;
    $(this).parents(".submitBlock").siblings(".acctRuleWrap").find(".redCircle").each(function (index) {
        if (!$(this).hasClass("hide")) {
            content = $(this).parents(".choiceBox").siblings(".acctContent").children("span").html();
            // console.log(content);
            ListIndex = index + 1
            return
        }
    })
    if ($(".acctRuleLiBrary").attr("type") == "gkd") {
         var model_one = content.charAt(0);
         var equalSymbolIndex = content.indexOf("=");
         var model_two = content.substring(1,equalSymbolIndex);
         // alert($("#div4").html().indexOf("button")==-1)
         if($(".new_model:last").find(".drag_child3").html().indexOf("button")==-1){
            $(".new_model:last").remove()
         }
         if($(".new_model:last").find(".drag_child3").attr("id")){
             eleId = parseInt($(".new_model:last").find(".drag_child3").attr("id").substring(3))+1;
         }
         var ruleBtnList = $(".gkdRuleLiBrary .elecRuleBtnWrap").find(".ruleBtnList" + ListIndex).html()//截取字符串
         var ruleContent = ruleBtnList.substring(ruleBtnList.indexOf("=</button>")+10)//找到等号的位置进行截取
        $('.new_label').append(` <div class="new_model" id="newModel"><button class="model_one">${model_one}</button> <input class="model_two" type="text" value="${model_two}"> <span class="model_three">=</span> <div id="div${eleId}" class="drag_child model_f drag_left drag_child3" ondragover="allowDrop(event)" ondrop="drop(event)">${ruleContent}</div><button class="btn input-distance templatesBtn model_six" type="gkd\"> 存入模板</button><button class="model_five delBtn">删除</button></div>`)
    }
    var str = (content.replace(/\ +/g, "").split(""));
    var arr = []
    var patt1 = new RegExp("[\u4e00-\u9fa5]");
    var str1;
    for (var i = 0; i < str.length; i++) {
        console.log(str[i])
        if (patt1.test(str[i])) {
            str1 += str[i]
        } else {
            arr.push(str1);
            arr.push(str[i])
            str1 = ''
        }
    }
    // console.log(arr)
    $(".acctRuleLiBrary").addClass("hide");
})




function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d.*(\-)]/g, "");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d\d\d\d).*$/, '$1$2.$3');//只能输入两个小数
    // if (obj.value.indexOf(".") < 0 && obj.value != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
    //     obj.value = parseFloat(obj.value);
    // }
}


$(".nameConfirmBtn").click(function () {
    if ($(this).parents(".acctRuleModal").attr("type") == "gkd"){
        var ruleName = $(".ruleName").val();
        var acctRule = $(".finalRule3").html();
        // alert(ruleName);
        if (ruleName == "") {
            alert("请填写规则名称");
            return;
        }
        var acctRule = $(".finalRule3").html();
        var ruleType = "2"
        $.ajax({
            "type": "POST",
            "url": prefix + "/saveAcctRuleRepository",
            "data": {
                operatorStationId: $("#operatorStationId").val(),
                tenantOperatorCode: $("#tenantOperatorCode").val(),
                tenantCode: $("#tenantCode").val(),
                ruleName: ruleName,
                acctRule: acctRule,
                ruleType: 2,
            },
            "success": function (data) {
                if (data.status == "200") {
                    layer.msg("添加成功");
                    $(".acctRuleNameModal").addClass("hide");
                    listAcctRuleRepository(ruleType,'2');
                }
            }
        })
    }
})




